package cn.i96688.scanclient.barcode;
import java.util.HashMap;
import java.util.Map;

import cn.i96688.scanclient.bean.PayLog;

public class BarcodeKeyboardListener{
//	private Logger log=Logger.getLogger(BarcodeKeyboardListener.class);
    private StringBuilder barcode;
    private long start;
    private Map<Integer,Integer> keyToLetter=new HashMap<Integer,Integer>();
    private static int maxScanTime=200;
    private static int barcodeMinLength=6;
    public BarcodeKeyboardListener(){
        keyToLetter.put(48,0);
        keyToLetter.put(49,1);
        keyToLetter.put(50,2);
        keyToLetter.put(51,3);
        keyToLetter.put(52,4);
        keyToLetter.put(53,5);
        keyToLetter.put(54,6);
        keyToLetter.put(55,7);
        keyToLetter.put(56,8);
        keyToLetter.put(57,9);
    }
    public void onKey(int keyCode) {
        Integer letter=keyToLetter.get(keyCode);
        if(barcode==null){
            barcode=new StringBuilder();
            start=System.currentTimeMillis();
        }
        long cost=System.currentTimeMillis()-start;
        if(cost > maxScanTime){
            barcode=new StringBuilder();
            start=System.currentTimeMillis();
        }
        if (keyCode >= 48 && keyCode <= 57) {
            barcode.append(letter);
        }
        if (keyCode == 13) {
            if(barcode.length() >= barcodeMinLength && cost < maxScanTime){
                cost=System.currentTimeMillis()-start;
                PayLog.getInstance().addLog("扫条码["+barcode.toString()+"]消耗时间： "+cost);
                BarcodeConsumer.getInstance().consume(barcode.toString());
            }

            barcode=new StringBuilder();
        }
    }
}
